import Model from '../../abstract';

export default class ModelCatalogOptionValue extends Model {
      
      constructor() {
            super();
            this.mainTable = 'product_option_value';
            this.pk = 'value_id';
            this.serverPk = 'server_value_id';
      }

      /**
       * 获取option values
       */
      async getValues(optionId) {
            return await this.fetchRows("SELECT * FROM `product_option_value` WHERE `option_id` = ? ORDER BY `sort_order` ASC", [optionId]);
      }

      /**
       * 保存商品option values
       */
      async saveValues(optionId, values = []) {
            if (optionId > 0) {
                  if (!Array.isArray(values)) {
                        values = [];
                  }
                  for (value of values) {
                        await this.saveValue(optionId, value);
                  }
            }
      }

      /**
       * 保存商品option
       */
      async saveValue(optionId, value) {
            let valueId = 0;
            if (optionId > 0 && typeof(value) == 'object') {
                  value.option_id = optionId;
                  valueId = parseInt(value.value_id);
                  valueId = await this.save(value, valueId);
            }
            return valueId;
      }

      /**
       * 保存商品option values
       */
      async saveValuesByServerId(optionId, values = []) {
            if (optionId > 0) {
                  if (!Array.isArray(values)) {
                        values = [];
                  }
                  for (value of values) {
                        await this.saveValueByServerId(optionId, value);
                  }
            }
      }

      /**
       * 保存商品option
       */
      async saveValueByServerId(optionId, value) {
            let valueId = 0;
            if (optionId > 0 && typeof(value) == 'object') {
                  value.option_id = optionId;
                  serverValueId = parseInt(value.server_value_id);
                  valueId = await this.saveByServerPk(value, serverValueId);
            }
            return valueId;
      }

      /**
       * 按照valueId删除
       */
      async removeValues(optionId) {
            return await this.delete(this.mainTable, {option_id: parseInt(optionId)});
      }

}